package com.cgs.query.client.remote

import com.cgs.query.exception.QueryException
import com.cgs.query.handler.RemoteHandler
import com.cgs.query.handler.Request
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.util.concurrent.atomic.AtomicLong

class RemoteInvocationHandler(private val remoteHandler: RemoteHandler) : InvocationHandler {

    private val sequence = AtomicLong(1)

    override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? {
        return if (method != null) {
            skipMethod(method.name) ?: {
                val response = remoteHandler.transport(Request(sequence.getAndIncrement(), method.name, args?.toList()
                        ?: listOf(), method.returnType))
                if (response.exception != null) {
                    throw QueryException("服务端返回错误:${response.exception!!.cause!!.message}", response.exception!!.cause!!)
                }
                response.result
            }()
        } else {
            null
        }
    }

    private fun skipMethod(methodName: String): Any? {
        return when (methodName) {
            "hashCode" -> proxyName.hashCode()
            "toString" -> proxyName
            "equals" -> false
            else -> null
        }
    }
}

const val proxyName = "com.cgs.query.service.IQueryService\$proxy0"